package com.anysoft.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.webkit.WebView;

/**
 * Created by lty on 2018/6/8.
 */

public class CustomWebView extends WebView {

    private OnLoadFinishListener mOnLoadFinishListener;

    public interface OnLoadFinishListener{
        public void onLoadFinish();
    }

    private boolean isRendered = false;


    public CustomWebView(Context context) {
        super(context.getApplicationContext());
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context.getApplicationContext(), attrs);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context.getApplicationContext(), attrs, defStyleAttr);
    }

    /**
     * 为了解决android4.4手机webview的onPageFinished()方法被执行多次导致的奔溃
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(!isRendered){
            isRendered = getContentHeight() > 0;
            if(mOnLoadFinishListener!= null){
                mOnLoadFinishListener.onLoadFinish();
            }
        }
    }

    public void setOnLoadFinishListener(OnLoadFinishListener onLoadFinishListener){
        this.mOnLoadFinishListener = onLoadFinishListener;
    }
    
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (scrollWebViewListener != null) {
            scrollWebViewListener.onScrollChanged(l, t, oldl, oldt);
        }
    }
    
    private OnScrollWebViewListener scrollWebViewListener;
    
    public void setOnScrollWebViewListener(OnScrollWebViewListener listener){
        this.scrollWebViewListener = listener;
    }
    
    public interface OnScrollWebViewListener{
        void onScrollChanged(int l, int t, int oldl, int oldt);
    }
}
